<template>
  <van-watermark v-if="user.shopName" :content="user.shopName" :width="200" :gap-x="20" opacity="0.5"></van-watermark>
  <!-- 头部比赛信息 -->
  <div class="match_header van-safe-area-top">
    <div class="row_info flexCenter">
      <van-icon name="arrow-left" class="back" @click="b.back" />
      <p class="center_tit">
        <span class="date" v-if="info.issue_num">{{ info.issue_num }}</span>
        <span class="date" v-else>{{ info.week }}{{ info.week_no }}</span>
        <span class="cup">{{ info.cup }}</span>
        <span class="date" v-if="info.stime">{{ format(info.stime * 1000, "HH:mm") }}</span>
      </p>
    </div>
    <div :class="['mainInfo', 'flexCenter', { 'reverse': info.types == 2 }]" v-if="info.home">
      <div class="left flexCrossCenter">
        <span class="teamName">{{ info.home }}</span>
        <van-image class="icon" v-if="info.h_icon" :src="`${globe.staticDomain}/${info.h_icon}`" fit="contain" />
        <van-image class="icon" v-else :src="match_home_default" fit="contain" />
      </div>
      <span class="vs" v-if="info.status == 0">VS</span>
      <span class="vs r" v-else>{{ info.types == 2 ? (info.guest_full + "-" + info.home_full) : (info.home_full + "-"
        +
        info.guest_full) }}</span>
      <div class="right flexCrossCenter">
        <van-image class="icon" v-if="info.g_icon" :src="`${globe.staticDomain}/${info.g_icon}`" fit="contain" />
        <van-image class="icon" v-else :src="match_guest_default" fit="contain" />
        <span class="teamName">{{ info.guest }}</span>
      </div>
    </div>
    <div class="TabsBox flexCrossCenter" v-if="art.matchList.length>0">
      <div class="weekNo flexCenter">{{ transWeek(info.wtime) }}</div>
      <van-tabs v-model:active="activeMatch" color="#FF5252" title-active-color="#FF5252" title-inactive-color="#ADADAD"
        class="rightTab" @click-tab="tabChange">
        <van-tab v-for="item in art.matchList" :title="`${item.session || item.week_no}`" :name="item.id"
          :key="item.id"></van-tab>
      </van-tabs>
    </div>
  </div>
  <div class="header_holder van-safe-area-top"></div>
  <!-- 比赛详细分析 -->
  <div class="detailPage">
    <!-- 足、篮 -->
    <template v-if="isNewNc">
      <div class="block" v-for="(item, i) in contentList" :key="i">
        <div class="title" v-if="item.title">
          <span class="cn">{{ item.title }}</span>
          <span class="en" v-if="type == 'football'">{{ football_en[`c${i+1}`].toUpperCase() }}</span>
          <span class="num">{{ numberToEnglish(i+1) }}</span>
        </div>
        <p v-html="item.content"></p>
      </div>
      <div class="block" v-if="showTotalPre">
        <div class="title zh">
          <span class="cn">综合分析</span>
          <span class="en">FORECAST RESULTS</span>
          <span class="num">{{ numberToEnglish(contentList.length+1) }}</span>
        </div>
        <template v-for="p in pmArr" :key="p.key">
          <p v-if="info[p.key]">
            <span class="label">{{ p.val }}：</span>
            <span class="t" v-if="p.key == 'p_hdc' && Number(info.rq)">({{ info.rq }})</span>
            <span class="t" v-else-if="p.key == 'p_hilo' && Number(info.toalsp)">({{ info.toalsp }})</span>
            <span v-for="(pm, i) in info[p.key].split(',')" class="pm">
              <template v-if="i > 0"> / </template>{{ playRes[pm] }}
            </span>
          </p>
        </template>
      </div>
      <div class="block" v-if="type == 'football' && info.summary">
        <div class="title">
          <span class="cn">冷门预警</span>
          <span class="en">COLD WARNING</span>
          <span class="num">{{ numberToEnglish(contentList.length + 2) }}</span>
        </div>
        <div class="flexCrossCenter">
          <p class="col">低赔变动：<b>{{ info.dp }}</b></p>
          <p class="col">5%+机构：<b>{{ info.num }}</b></p>
        </div>
        <p v-html="info.summary" class="cold_summary"></p>
      </div>
    </template>
    <!-- 传足 type: 2 -->
    <template v-else>
      <div class="block" v-for="(item, i) in matchData[2]" :key="i">
        <div class="title" v-if="item[0]">
          <span class="cn">{{ item[0] }}</span>
          <span class="num">{{ numberToEnglish(i + 1) }}</span>
        </div>
        <p v-html="item[1]"></p>
      </div>
    </template>
    <van-image class="footImg" :src="getImgUrl('computer.jpg')" fit="cover" @click="redirect('/calculator', '计算器')" />
    <p class="tips">*分析助手仅提供赛事数据分析整理，不做任何引导</p>
  </div>
  <!-- 特殊店铺广告提示 -->
  <template v-if="showFixedTip && user.homeAdUrl">
    <van-image class="fixedTip" src="/ad.gif" fit="cover" @click="backWenCai()" />
    <div class="fixedTipHolder van-safe-area-bottom"></div>
  </template>
</template>

<script setup>
import useBack from '@/hooks/back';
import { matchDetail } from '@/api/calc'
import { format } from 'date-fns';
import { useRouter, useRoute } from 'vue-router'
import { useUserStore, useGlobeStore, useArtStore } from '@/stores'
import { getImgUrl, numberToEnglish } from "@/utils/helper"
import { decryptData, getWeek } from "@/utils/calc"
import { extractText } from "@/utils/text"
import { playRes, footballPm, basktballPm } from "@/utils/data"
import match_guest_default from '@/assets/image/shopColorTools/match_guest_default.png'
import match_home_default from '@/assets/image/shopColorTools/match_home_default.png'

const b = useBack();
const route = useRoute()
const router = useRouter()
const art = useArtStore();
const user = useUserStore()
const globe = useGlobeStore();
const info = ref({});
const matchData = ref([]); // 传足
const contentList = ref([]); // 足、篮内容
const activeMatch = ref(""); // 当前比赛
let { id, type } = route.params;
const isNewNc = ["football", "basketball"].includes(type);
const showFixedTip = computed(() => user.shopUuid.includes(user.i));
let strary = [];
const football_en = {
  c1: "Paper strength",
  c2: "achievements",
  c3: "Attack & Defense",
  c4: "Event performance",
  c5: "Confrontation",
}
const pmArr = computed(() => type == "football" ? footballPm : basktballPm)
const showTotalPre = computed(()=>{
  if (type =="football"){
    return footballPm.some(pm => info.value[pm.key])
  } else if (type == "basketball"){
    return basktballPm.some(pm => info.value[pm.key])
  }else{
    return false
  }
})

function transWeek(time) {
  if (!time) return;
  const millsecond = time * 1000;
  return getWeek(new Date(millsecond));
}

// 先根据比赛信息得到正确的文本顺序
function rearrangeContent() {
  const match = info.value;
  for (let i = 0; i < match.items.length; i++) {
    const iItem = match.items[i];
    // 得到正确的文本顺序 索引数组
    const kAry = iItem.k.split(user.spaceMark)
    const decryptedIndex = decryptData({ da: kAry[1], de: kAry[0] })
    if (isNewNc){ // 足球、篮球
      const arr = []
      for (var key in iItem.content){
        const _cont = []
        const elements = iItem.content[key].split('，');
        for (let k = 0; k < decryptedIndex[key][1].length; k++) {
          const el = decryptedIndex[key][1][k];
          _cont[el] = elements[k]
        }
        arr.push({
          sort: Number(key.replace("c", '')),
          title: art.content_types[key],
          content: _cont.join('，').replace(/\r\n?/g, '<br>').replace('总结：', '<b>总结：</b>'),
        })
      }
      contentList.value = arr.sort((a, b) => a.sort - b.sort)
    }else{ // 传足
      // 拼接记录新的文本信息
      const obj = {
        type: iItem.type,
        content: [],
        type_name: iItem.type_name,
        'home': match.home.replace(/\s/g, ''),
        'guest': match.guest.replace(/\s/g, '')
      }
      // for (let j = 0; j < iItem.content.length; j++) {}
      for (let j in iItem.content){
        const _cont = []
        const elements = iItem.content[j].split('，');
        for (let k = 0; k < decryptedIndex[j][1].length; k++) {
          const el = decryptedIndex[j][1][k];
          _cont[el] = elements[k]
        }
        obj.content[decryptedIndex[j][0]] = _cont.join('，')
      }
      // 处理文本
      match[iItem.type] = extractText(obj, type, strary)
      matchData.value = match
    }
  }
}

function redirect(path, label) {
  router.push(path);
  user.log({ type: 'event', action: 'click', opt_label: label, target_url: path});
}
async function queryDetail(){
  // 先请求比赛详情
  const matchData = await matchDetail({ cid: globe.cid, type, i: user.i, version: 2, id })
  if (matchData) {
    const { ids, match, content_types } = matchData;
    art.setContentTypes(content_types);
    info.value = { ...match, ids };
    activeMatch.value = match.id;
    const tit = match.types == 2 ? (match.guest + 'vs' + match.home) : (match.home + 'vs' + match.guest);
    document.title = `赛事分析-${tit}`;
    if (art.matchList.length == 0 && match.wtime) {
      // 比赛列表为空 就请求列表
      await art.queryMatchs({
        cid: globe.cid,
        type,
        i: user.i,
        version: 2,
        wtime: match.wtime,
        log: 1,
      })
    }
    // 根据比赛信息得到正确的文本顺序
    strary = user.decryptedStrs.filter((_, idx) => ids.includes(idx))
    rearrangeContent()
  }
}
function tabChange(item){
  const { name } = item
  if(id==name) return;
  router.replace(`/mdetail/${type}/${name}`);
  // 请求详情
  id = String(name);
  queryDetail()
}
// watch(() => route.params.id, (val)=>{
//   console.log(11111, val);
//   queryDetail()
// })
onMounted(queryDetail)
onBeforeUnmount(()=>{
  user.updateShareInfo();
})
</script>

<style lang="less" scoped>
@import "@/assets/varables.less";
.match_header{
  width: 100%;
  min-height: 132px;
  background: linear-gradient(180deg, #ffebeb, #fff 60%);
  color: #141414;
  border-bottom: 1px solid #ebebeb;
  position: fixed;
  z-index: 2;
  .row_info{
    height: 44px;
    position: relative;
    .back{
      font-size: 24px!important;
      color: #141414;
      position: absolute;
      left: 10px;
      top: 10px;
    }
    .cup{
      margin: 0 6px;
    }
    .center_tit{
      font-size: 12px;
    }
  }
  .mainInfo {
    height: 44px;
    border-bottom: 1px solid #ebebeb;
    &.reverse {
      flex-direction: row-reverse !important;
      .left,.right{
        flex-direction: row-reverse !important;
      }
    }
    .teamName {
      font-size: 14px;
      line-height: 1;
      font-weight: 700;
      margin: 0 4px;
      word-break: break-all;
    }
    .icon {
      width: 24px;
      height: 24px;
      margin: 0 4px;
    }
    .left,
    .right {
      flex: 1;
    }
    .left {
      justify-content: flex-end;
      .teamName {
        text-align: right;
      }
    }
    .vs {
      font-size: 14px;
      font-weight: bold;
      margin: 0 6px;
      &.r{
        font-size: 16px!important;
        color: #FF5252;
      }
    }
  }
  .TabsBox{
    width: 100%;
    height: 44px;
    background: #fff;
    .weekNo{
      min-width: 56px;
      width: 56px;
      font-size: 12px;
      border-right: 1px solid #ebebeb;
    }
    .rightTab{
      width: 319px;
      --van-tab-font-size: 12px;
      :deep(.van-tab){
        width: 20%;
      }
      :deep(.van-tabs__nav--line) {
        padding-bottom: 0 !important;
      }
      :deep(.van-tabs__line) {
        width: 22px;
        height: 8px;
        border-radius: 4px;
        bottom: -4px;
      }
    }
  }
}
.header_holder{
  box-sizing: content-box;
  min-height: 132px;
}
.detailPage{
  padding: 0 8px 16px;
  color: #141414;
  overflow: hidden;
  background-color: #f7f8fa;
  .block{
    width: 359px;
    min-height: 36px;
    background-color: #fff;
    border-radius: 0 0 12px 12px;
    position: relative;
    padding: 0 24px 12px;
    margin-top: 74px;
    .t {
      margin-right: 6px;
      font-weight: 700;
    }
    .col{
      width: 50%;
    }
    // .cold_summary{
    //   margin: 10px -24px -12px;
    //   padding: 12px 24px;
    //   background-color: #e5e5e5;
    //   border-radius: 0 0 12px 12px;
    // }
  }
  .title{
    position: absolute;
    left: 0;
    top: -60px;
    width: 359px;
    height: 94px;
    background: url("@/assets/img/panel.png") center top no-repeat;
    background-size: cover;
    font-size: 14px;
    font-weight: 900;
    padding: 14px 24px 64px;
    display: flex;
    align-items: center;
    &.zh{
      background-image: url("@/assets/img/panel_zh.png");
    }
    .cn{
      font-size: 16px;
      font-weight: 900;
      color: #fff;
    }
    .en{
      font-weight: 900;
      margin-left: 10px;
      letter-spacing: -1px;
      @gradientArr: #ffffff00 0%, #ffffff3d 100%;
      .text-gradient(0deg, @gradientArr, #ffbf00);
    }
    .num{
      font-size: 18px;
      font-weight: 900;
      position: absolute;
      right: 10px;
      top: 10px;
      @gradientArr: #f5f5f500 0%, #f5f5f5 100%;
      .text-gradient(90deg, @gradientArr, #f5f5f5);
    }
  }
  p{
    font-size: 14px;
    line-height: 24px;
    word-break: break-all;
    position: relative;
    z-index: 1;
  }
  .label{
    display: inline-block;
    width: 80px;
  }
  .pm{
    font-weight: 700;
  }
  .footImg{
    display: block;
    width: 100%;
    margin-top: 8px;
    border-radius: 10px;
    overflow: hidden;
  }
  .tips{
    padding: 16px 0 0;
    text-align: center;
    font-size: 10px;
    line-height: 1;
    color: #D6D6D6;
  }
}
.fixedTip {
  position: fixed;
  left: 0px;
  bottom: 0px;
  width: 100%;
  height: 104px;
  z-index: 2;
}
.fixedTipHolder {
  height: 104px;
}
.notice {
  .notify_text{
    font-size: 12px!important;
  }
  .close {
    font-size: 20px!important;
    margin-left: 10px;
  }
}
</style>
